from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ReadOnlyModelViewSet

from meiduo_admin.serializers.orders import OrderSerializers
from orders.models import OrderInfo
from meiduo_admin.utils.pagination import MeiduoPagination


class OrderView(ReadOnlyModelViewSet):
    def get_queryset(self):
        queryset = OrderInfo.objects
        keyword = self.request.query_params.get('keyword')

        if keyword:
            queryset = queryset.filter(order_id__contains=keyword)

        queryset = queryset.order_by('-create_time')
        return queryset

    serializer_class = OrderSerializers
    pagination_class = MeiduoPagination

    @action(methods=['put'], detail=True)
    def status(self, request, *args, **kwargs):
        instance = self.get_object()
        status = request.data.get('status')
        instance.status = status
        instance.save()

        return Response({
            'order_id': instance.order_id,
            'status': instance.status
        })
